/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * WorkScheduleController
 * 工作日程表
 * 修改纪录
 * 2020-10-24 版本：1.0 zhanglongfei 创建。
 *
 * @version 版本：1.0
 * @author 作者：zhanglongfei
 * 创建日期：2020-10-24
 */
package com.topscomm.work.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.*;
import com.topscomm.cbo.service.ICboItemDetailsService;
import com.topscomm.meet.dto.ConfirmInfo;
import com.topscomm.meet.service.IMeetJoinConfirmService;
import org.codehaus.jackson.map.ser.BeanSerializerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.base.BaseSystemConst.BaseOperateTypeEnum;
import com.topscomm.base.pojo.BasePermissionManageEntity;
import com.topscomm.base.pojo.BaseTeamUserEntity;
import com.topscomm.base.service.IBaseOperateRecordService;
import com.topscomm.base.service.IBasePermissionManageService;
import com.topscomm.base.service.IBaseTeamUserService;
import com.topscomm.base.service.impl.BaseShareManageService;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboUserRoleService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.meet.pojo.MeetManageEntity;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.work.WorkSystemConst.WorkColorEnum;
import com.topscomm.work.WorkSystemConst.WorkSourceTypeEnum;
import com.topscomm.work.controller.auto.WorkScheduleControllerAuto;
import com.topscomm.work.pojo.WorkScheduleEntity;

/**
 * @author: zhanglongfei
 * @date: 2020-10-24
 * @description:工作日程表Controller
 * @modify:
 */
@RestController
@RequestMapping("work/schedule")
public class WorkScheduleController extends WorkScheduleControllerAuto implements IWorkScheduleController {
	@Autowired
	private IBaseOperateRecordService baseOperateRecordService;
	@Autowired
	private ICboDeptService cboDeptService;
	@Autowired
	private ICboUserService cboUserService;
	@Autowired
	private ICboUserRoleService cboUserRoleService;
	@Autowired
	private IBaseTeamUserService baseTeamUserService;
	@Autowired
	private IBasePermissionManageService basePermissionManageService;
	@Autowired
	private ICboDeptService cbodeptservice;
	@Autowired
	IMeetJoinConfirmService meetJoinConfirmService;
	@Autowired
	ICboItemDetailsService cboItemDetailsService;

	/**
	 * @author: zhanglongfei
	 * @date: 2020-10-24
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_sourceapp")) {
			String value = paraMap.get("qry_sourceapp").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceapp = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourcetype")) {
			String value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourcetype = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourceid")) {
			String value = paraMap.get("qry_sourceid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceid = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_key")) {
			String value = paraMap.get("qry_key").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (name like '%{0}%' or tags like '%{1}%') ", value, value);
		}
		if (paraMap.containsKey("qry_scheduletype")) {
			String value = paraMap.get("qry_scheduletype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and scheduletype = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_range")) {
			String start = paraMap.get("qry_begintime").toString();
			String end = paraMap.get("qry_endtime").toString();
			sql.appendSingle(" and (begintime <= {0} and endtime >= {1})", SQLAdapter.toDateLong(end), SQLAdapter.toDateLong(start));
		} else {
			if (paraMap.containsKey("qry_begintime")) {
				String value = paraMap.get("qry_begintime").toString();
				if (!StringUtil.isEmpty(value))
					sql.appendSingle(" and begintime >= {0} ", SQLAdapter.toDateLong(value));
			}
			if (paraMap.containsKey("qry_endtime")) {
				String value = paraMap.get("qry_endtime").toString();
				if (!StringUtil.isEmpty(value))
					sql.appendSingle(" and endtime <= {0}", SQLAdapter.toDateLong(value));
			}
		}
		if (paraMap.containsKey("qry_markcolor")) {
			String value = paraMap.get("qry_markcolor").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and markcolor = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_usercode")) {
			String value = paraMap.get("qry_usercode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and usercode = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_handleusercode")) {
			String value = paraMap.get("qry_handleusercode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and handleusercode = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_notself")) {
			sql.appendSingle(" and createuser <> '{0}' ", this.getUserBean().getUser().getId());
		}
		if (paraMap.containsKey("qry_self")) {
			sql.appendSingle(" and handleusercode = '{0}' ", this.getUserBean().getUser().getCode());
		}
		return sql.toString();
	}

	/**
	 * @description:获取日程列表,返回List
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年10月27日下午2:10:02
	 * @modify:
	 */
	@GetMapping(value = "/queryScheduleList")
	public ResponseResult<Object> queryScheduleList(@RequestParam(required = false) Map<String, Object> paraMap) {
			List<Map<String, Object>> result = queryScheduleListProcess(paraMap);
			return ResponseResult.ok(result);
	}

	/**
	 * @description: 获取日程列表的实现过程
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月25日下午8:30:18
	 * @modify:
	 */
	private List<Map<String, Object>> queryScheduleListProcess(Map<String, Object> paraMap) {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		String codeString = this.getUserBean().getUser().getCode();
		paraMap.put("qry_currentuser", this.getUserBean().getUser().getId());
		paraMap.put("qry_currentusercode", codeString);
		String userCode = "";
		if (paraMap.containsKey("qry_usercode")) {
			// 整理搜索条件
			userCode = ConvertUtil.convertToString(paraMap.get("qry_usercode"));
			generateUserQueryData(userCode, paraMap);
		}
		result = this.service.queryMap(paraMap, "queryMapForCalendar");
		this.service.setDispFields(result);
		List<Map<String, Object>> colorList = cboItemDetailsService.queryMapByWhere("itemid  = (select id from cboitems  item where item.code = 'WorkColor' )");
		for (Map<String, Object> map : result) {
			String handleUserCode = ConvertUtil.convertToString(map.get(WorkScheduleEntity.FieldHandleusercode));
			String handleUserName = ConvertUtil.convertToString(map.get(WorkScheduleEntity.FieldHandleusername));
			String sourceType = ConvertUtil.convertToString(map.get(WorkScheduleEntity.FieldSourcetype));
			String sourceId = ConvertUtil.convertToString(map.get(WorkScheduleEntity.FieldSourceid));
			// 获取任务的来自部门与人员
			String taskFrom = getRemindSource(handleUserCode, handleUserName, sourceType);
			//获取参会人员
			ConfirmInfo info = null;
			if(sourceType.contentEquals(MeetManageEntity.tableName)){
				info = meetJoinConfirmService.loadJoinInfo(ConfirmInfo.builder().sourceType(sourceType).sourceId(sourceId).userCode(userCode).build());
			}
			map.put("taskfrom", taskFrom);
			map.put("self", codeString.equals(handleUserCode));
			if (WorkColorEnum.MyMark.equals(map.get(ConvertUtil.convertToString("markcolor")))) {
				Map<String, Object> color = colorList.stream().filter(item -> item.get("code").toString().equals(WorkColorEnum.MyMark)).findFirst().orElse(null);
				map.put("dispmarkcolor", color == null ? "" : color.get("name"));
				//创建人
			} else if (handleUserCode.equals(userCode)) {
				map.put("markcolor", WorkColorEnum.MyCreate);
				Map<String, Object> color = colorList.stream().filter(item -> item.get("code").toString().equals(WorkColorEnum.MyCreate)).findFirst().orElse(null);
				map.put("dispmarkcolor", color == null ? "" : color.get("name"));
				map.put("dispmarktext", color == null ? "" : color.get("extendfield1"));
				//拒绝参会
			} else if( info!=null && Boolean.FALSE.equals(info.getConfirmState())) {
				map.put("markcolor", WorkColorEnum.MyRefuse);
				Map<String, Object> color = colorList.stream().filter(item -> item.get("code").toString().equals(WorkColorEnum.MyRefuse)).findFirst().orElse(null);
				map.put("dispmarkcolor", color == null ? "" : color.get("name"));
				map.put("dispmarktext", color == null ? "" : color.get("extendfield1"));
				//参与人
			} else {
				map.put("markcolor", WorkColorEnum.MyJoin);
				Map<String, Object> color = colorList.stream().filter(item -> item.get("code").toString().equals(WorkColorEnum.MyJoin)).findFirst().orElse(null);
				map.put("dispmarkcolor", color == null ? "" : color.get("name"));
				map.put("dispmarktext", color == null ? "" : color.get("extendfield1"));
			}
		}
		return result;
	}

	/**
	 * @description: 获取任务的来自部门与人员
	 * @param handleusercode
	 * @param handleusername
	 * @return
	 * @author: maxiaodong
	 * @date: 2020年12月2日下午1:48:25
	 * @modify:
	 */
	private String getRemindSource(String handleusercode, String handleusername, String sourcetype) {
		String taskFrom = "";
		if ("".equals(sourcetype) || sourcetype == null || WorkSourceTypeEnum.WorkTask.equals(sourcetype)) {
			StringBufferProxy queryFromUserSql = new StringBufferProxy();
			queryFromUserSql.appendSingle("code in ('{0}')", handleusercode);
			// 获取来源
			List<CboUserEntity> cboUserEntityFromList = this.cboUserService.queryByWhere(queryFromUserSql.toString());
			if (cboUserEntityFromList.size() == 1) {
				// 获取部门描述
				CboDeptEntity cboDeptEntity = this.cbodeptservice.queryObjectByWhere("id in ('" + cboUserEntityFromList.get(0).getDeptid() + "')");
				taskFrom = cboDeptEntity.getFullname() + "\\" + handleusername;
			}
		} else if (WorkSourceTypeEnum.MeetManageType.equals(sourcetype)) {
			taskFrom = handleusername;
		}
		return taskFrom;
	}

	/**
	 * @description: 获取日程列表，返回Map
	 * @param paraMap
	 * @return
	 * @author: maxiaodong
	 * @date: 2020年11月25日下午8:32:55
	 * @modify:
	 */
	@GetMapping(value = "/queryScheduleListMap")
	public ResponseResult<Object> queryScheduleListMap(@RequestParam(required = false) Map<String, Object> paraMap) {
			List<Map<String, Object>> result = queryScheduleListProcess(paraMap);
			// 重新获取冲突检测的开始时间与结束时间（所有开始时间的最小时间与所有结束时间的最大时间）。
			Date beginTimeBottom = null;
			Date endTimeTop = null;
			for (Map<String, Object> resultItem : result) {
				Date begintime = DateUtil.stringToDate(ConvertUtil.convertToString(resultItem.get("begintime")));
				Date endtime = DateUtil.stringToDate(ConvertUtil.convertToString(resultItem.get("endtime")));
				// 获取最小的开始时间
				if (beginTimeBottom == null) {
					beginTimeBottom = begintime;
				} else {
					if (begintime.getTime() < beginTimeBottom.getTime()) {
						beginTimeBottom = begintime;
					}
				}
				// 获取最大的结束时间
				if (endTimeTop == null) {
					endTimeTop = endtime;
				} else {
					if (endtime.getTime() > endTimeTop.getTime()) {
						endTimeTop = endtime;
					}
				}
			}
			// 重新查询并对结果进行时间冲突检测
			paraMap.put("begintime", beginTimeBottom);
			paraMap.put("endtime", endTimeTop);
			List<Map<String, Object>> resultExpand = queryScheduleListProcess(paraMap);
			// 冲突信息
			Map<String, Object> conflicInfo = new HashMap<>();
			// 冲突的所有日期
			List<String> datesConflict = new ArrayList<>();
			// 冲突的所有id
			List<String> idsConflict = new ArrayList<>();
			int resultLength = resultExpand.size();
			// 移动端时间冲突检测
			for (int i = 0; i < resultLength; i++) {
				for (int j = i + 1; j < resultLength; j++) {
					Map<String, Object> resultI = resultExpand.get(i);
					Map<String, Object> resultJ = resultExpand.get(j);
					// resultI.put("conflictFlag", false);
					// resultJ.put("conflictFlag", false);
					Date begintimeConflict = null;
					Date endtimeConflict = null;
					// 获取比较条目的开始时间与结束时间
					Date begintime = DateUtil.stringToDate(ConvertUtil.convertToString(resultExpand.get(i).get("begintime")));
					Date endtime = DateUtil.stringToDate(ConvertUtil.convertToString(resultExpand.get(i).get("endtime")));
					Date begintimeOther = DateUtil.stringToDate(ConvertUtil.convertToString(resultExpand.get(j).get("begintime")));
					Date endtimeOther = DateUtil.stringToDate(ConvertUtil.convertToString(resultExpand.get(j).get("endtime")));
					// 进行时间比较，获取冲突的时间段,冲突id
					if (begintime.getTime() <= begintimeOther.getTime()) {
						// 开始时间在对比任务开始时间之前
						if (endtime.getTime() > begintimeOther.getTime() && endtime.getTime() <= endtimeOther.getTime()) {
							// 结束时间在对比任务开始时间之后，在对比任务结束时间之前
							begintimeConflict = begintimeOther;
							endtimeConflict = endtime;
						} else if (endtime.getTime() > endtimeOther.getTime()) {
							// 结束时间在对比任务结束时间之后
							begintimeConflict = begintimeOther;
							endtimeConflict = endtimeOther;
						}
					} else if (begintime.getTime() > begintimeOther.getTime() && begintime.getTime() < endtimeOther.getTime()) {
						// 开始时间在对比任务开始时间之后，在对比任务结束时间之前
						if (endtime.getTime() > begintimeOther.getTime() && endtime.getTime() < endtimeOther.getTime()) {
							// 结束时间在对比任务开始时间之后，在对比任务结束时间之前
							begintimeConflict = begintime;
							endtimeConflict = endtime;
						} else if (endtime.getTime() > endtimeOther.getTime()) {
							// 结束时间在对比任务结束时间之后
							begintimeConflict = begintime;
							endtimeConflict = endtimeOther;
						}
					}
					if (begintimeConflict != null && endtimeConflict != null) {
						resultI.put("conflictFlag", true);
						resultJ.put("conflictFlag", true);
						String workScheduleItemId = ConvertUtil.convertToString(resultExpand.get(i).get("id"));
						String workScheduleItemOtherId = ConvertUtil.convertToString(resultExpand.get(j).get("id"));
						idsConflict.add(workScheduleItemId);
						idsConflict.add(workScheduleItemOtherId);
						Date DateConflict = DateUtil.stringToDate(DateUtil.dateToString(begintimeConflict, "yyyy-MM-dd"));
						// 获取冲突的日期
						Calendar calendar = Calendar.getInstance();
						while (DateConflict.getTime() <= endtimeConflict.getTime()) {
							datesConflict.add(DateUtil.dateToString(DateConflict, "yyyy-MM-dd"));
							calendar.setTime(DateConflict);
							calendar.add(Calendar.DAY_OF_MONTH, 1);
							DateConflict = calendar.getTime();
						}
					}
				}
			}
			// result数据中加入时间冲突的字段
			for (Map<String, Object> resultItem : result) {
				if (idsConflict.contains(ConvertUtil.convertToString(resultItem.get("id")))) {
					resultItem.put("conflictFlag", true);
				} else {
					resultItem.put("conflictFlag", false);
				}
			}
			Map<String, Object> resultMap = new HashMap<>();
			resultMap.put("dataList", result);
			idsConflict = idsConflict.stream().distinct().collect(Collectors.toList());
			datesConflict = datesConflict.stream().distinct().collect(Collectors.toList());
			conflicInfo.put("datesConflict", datesConflict);
			resultMap.put("conflictInfo", conflicInfo);
			return ResponseResult.ok(resultMap);
	}

	/**
	 * @description:查询数量
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月17日上午10:45:19
	 * @modify:
	 */
	@GetMapping(value = "/queryScheduleCount")
	public ResponseResult<Object> queryScheduleCount(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String codeString = this.getUserBean().getUser().getCode();
			paraMap.put("qry_currentuser", this.getUserBean().getUser().getId());
			paraMap.put("qry_currentusercode", codeString);
			String userCode = "";
			if (paraMap.containsKey("qry_usercode")) {
				// 整理搜索条件
				userCode = ConvertUtil.convertToString(paraMap.get("qry_usercode"));
				generateUserQueryData(userCode, paraMap);
			}
			int result = this.service.getCount(paraMap, "queryCountForCalendar");
			return ResponseResult.ok(result);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}
	/**
	 * @description:查询数量 非鉴权
	 * @param paraMap
	 * @return
	 * @author: xinfusuho
	 * @date: 2022年01月17日上午10:45:19
	 * @modify:
	 */
	@GetMapping(value = "/queryScheduleCountNoToken")
	public ResponseResult<Object> queryScheduleCountNoToken(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String codeString = ConvertUtil.convertToString(paraMap.get("usercode"));
			if(codeString.isEmpty()){
				throw new IllegalArgumentException("缺少usercode参数");
			}
			String idString = ConvertUtil.convertToString(cboUserService.queryObjectByWhere("code = '".concat(codeString).concat("'")).getId());
			paraMap.put("qry_currentuser", idString);
			paraMap.put("qry_currentusercode", codeString);
			//日程红点不查看已拒绝的
			paraMap.put("qry_filtertype",WorkColorEnum.MyRefuse);
			String userCode = "";
			if (paraMap.containsKey("qry_usercode")) {
				// 整理搜索条件
				userCode = ConvertUtil.convertToString(paraMap.get("qry_usercode"));
				generateUserQueryData(userCode, paraMap);
			}
			int result = this.service.getCount(paraMap, "queryCountForCalendar");
			return ResponseResult.ok(result);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}
	/**
	 * @description:查询数量 非鉴权
	 * @param paraMap
	 * @return
	 * @author: xinfusuho
	 * @date: 2022年01月17日上午10:45:19
	 * @modify:
	 */
	@GetMapping(value = "/queryScheduleCountNoTokenForAndroid")
	public ResponseResult<Object> queryScheduleCountNoTokenForAndroid(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String codeString = ConvertUtil.convertToString(paraMap.get("usercode"));
			if(codeString.isEmpty()){
				throw new IllegalArgumentException("缺少usercode参数");
			}
			String idString = ConvertUtil.convertToString(cboUserService.queryObjectByWhere("code = '".concat(codeString).concat("'")).getId());
			paraMap.put("qry_currentuser", idString);
			paraMap.put("qry_currentusercode", codeString);
			//日程红点不查看已拒绝的
			paraMap.put("qry_filtertype",WorkColorEnum.MyRefuse);
			String userCode = "";
			if (paraMap.containsKey("qry_usercode")) {
				// 整理搜索条件
				userCode = ConvertUtil.convertToString(paraMap.get("qry_usercode"));
				generateUserQueryData(userCode, paraMap);
			}
			int totalCount = this.service.getCount(paraMap, "queryCountForCalendar");
			HashMap<String,Object> result = new HashMap<>();
			result.put("totalCount",totalCount);
			return ResponseResult.ok(result);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/**
	 * @description:PC首页的统计功能
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月6日下午3:46:15
	 * @modify:
	 */
	@GetMapping(value = "/queryHomeStatic")
	public ResponseResult<Object> queryHomeStatic(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (paraMap.containsKey("qry_usercode")) {
				// 整理搜索条件
				String userCode = ConvertUtil.convertToString(paraMap.get("qry_usercode"));
				generateUserQueryData(userCode, paraMap);
			}
			list = this.service.queryMap(paraMap, "queryMapForCalendar");
			Map<String, Object> result = new HashMap<>();
			result.put("schedule", list.size());
			result.put("meet", list.stream().filter(m -> MeetManageEntity.tableName.equals(ConvertUtil.convertToString(m.get("sourcetype")))).count());
			result.put("train", 0);
			return ResponseResult.ok(result);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/**
	 * @description:加载数据
	 * @return
	 * @author: donghang
	 * @date: 2019年8月8日上午11:13:01
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/load")
	public ResponseResult<Object> load(@RequestParam(required = false) Map<String, Object> paraMap) {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Map<String, Object> dataMap = this.service.queryMapById(paraMap.get("id").toString());
			afterLoad(dataMap);
			return ResponseResult.ok(dataMap);
	}
	/**
	 * @description: 查询单条记录后，查询当前用户的关注状态
	 * @param paraMap
	 * @author: zhanglongfei
	 * @date: 2020年10月30日下午3:49:23
	 * @modify:
	 */
	@Override
	protected void afterLoad(Map<String, Object> paraMap) {
		if (paraMap == null || ConvertUtil.convertToLong(paraMap.get("id")) <= 0) {
			throw new ServiceException("日程已删除");
		}
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendLineSingle("sourcetype='{0}' and sourceid='{1}' and operatetype='{2}' and usercode='{3}'", WorkSourceTypeEnum.WorkSchedule, paraMap.get("id"), BaseOperateTypeEnum.Attention, this
				.getUserBean().getUser().getCode());
		int count = baseOperateRecordService.getCount(sql.toString());
		if (count > 0) {
			paraMap.put("markcolor", WorkColorEnum.MyMark);
		} else {
			String handleUserCode = ConvertUtil.convertToString(paraMap.get(WorkScheduleEntity.FieldHandleusercode));
			if (handleUserCode.equals(this.getUserBean().getUser().getCode())) {
				paraMap.put("markcolor", WorkColorEnum.MyCreate);
			} else {
				paraMap.put("markcolor", WorkColorEnum.MyJoin);
			}
		}
	}

	/**
	 * @description:在工作台添加日历
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年10月27日下午5:12:03
	 * @modify:
	 */
	@RequestMapping(value = "/saveCalendar", method = { RequestMethod.POST, RequestMethod.PUT })
	public ResponseResult<Object> saveCalendar(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			if (StringUtil.isEmpty(ConvertUtil.convertToString(paraMap.get(WorkScheduleEntity.FieldHandleusercode)))) {
				paraMap.put(WorkScheduleEntity.FieldHandleusercode, this.getUserBean().getUser().getCode());
				paraMap.put(WorkScheduleEntity.FieldHandleusername, this.getUserBean().getUser().getName());
			}
			WorkScheduleEntity scheduleEntity = this.service.saveCalendarEntity(paraMap);
			return ResponseResult.ok(scheduleEntity);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * @description:用于日历拖动修改日期
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年10月29日下午5:43:40
	 * @modify:
	 */
	@RequestMapping(value = "/changeCalendarTime", method = { RequestMethod.POST })
	public ResponseResult<Object> changeCalendarTime(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			this.service.changeCalendarTime(paraMap);
			return ResponseResult.ok("成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * @author: zhanglongfei
	 * @date: 2020-10-24
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 * @description:生成用户查询数据
	 * @param userCode
	 * @param paraMap
	 * @author: zhanglongfei
	 * @date: 2020年11月6日下午3:49:01
	 * @modify:
	 */
	public void generateUserQueryData(String userCode, Map<String, Object> paraMap) {
		List<Long> roleidList = new ArrayList<Long>();
		List<String> teamidList = new ArrayList<String>();
		// 如果查询的是当前登录人的，直接添加，避免多余搜索
		String deptCodeString = "";
		//若当前userbean 为null即无鉴权，走查询 否则直接去userbean中数据
		if (this.getUserBean()!=null && userCode.equals(this.getUserBean().getUser().getCode())) {
			deptCodeString = this.getUserBean().getDept().getCode();
			for (CboRoleEntity roleEntity : this.getUserBean().getRoleList()) {
				roleidList.add(roleEntity.getId());
			}
		} else {
			CboUserEntity userEntity = cboUserService.queryObjectByWhere("code='" + userCode + "'");
			CboDeptEntity deptEntity = cboDeptService.queryById(String.valueOf(userEntity.getDeptid()));
			List<CboUserRoleEntity> roleList = cboUserRoleService.queryByWhere(CboUserRoleEntity.FieldUserid + "='" + userEntity.getId() + "'");
			deptCodeString = deptEntity.getCode();
			for (CboUserRoleEntity cboUserRoleEntity : roleList) {
				roleidList.add(cboUserRoleEntity.getRoleid());
			}
		}
		String deptWhereString = BaseShareManageService.createWhereDeptCheckInclude(BasePermissionManageEntity.FieldShareobjects, deptCodeString, ",");
		paraMap.put("qry_deptWhere", deptWhereString);
		paraMap.put("qry_roleidList", roleidList);
		List<BaseTeamUserEntity> teamList = baseTeamUserService.queryByWhere(BaseTeamUserEntity.FieldUsercode + "='" + userCode + "'");
		for (BaseTeamUserEntity baseTeamUserEntity : teamList) {
			teamidList.add(baseTeamUserEntity.getTeamid());
		}
		paraMap.put("qry_teamidList", teamidList);
	}

	@Override
	@DeleteMapping(value = "/delete")
	public ResponseResult<Object> delete(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String ids = ConvertUtil.convertToString(paraMap.get("ids"));
			// 删除时，提醒对方
			List<WorkScheduleEntity> scheduleList = this.service.queryByWhere(" id in (" + ids + ")");
			List<BasePermissionManageEntity> permissionManageList = basePermissionManageService
					.queryByWhere("sourceid in ('" + ids.replaceAll("\\,", "','") + "') and sourcetype='" + WorkSourceTypeEnum.WorkSchedule + "'");
			this.service.deleteByWhere(" id in (" + ids + ")");
			afterDelete(paraMap);
			if (scheduleList.size() == 1) {
				this.service.pushRemindTask(scheduleList.get(0), permissionManageList, null, false, true, getUserBean());
			}
			return ResponseResult.ok("删除成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * @description:从OA同步工作日程数据到Meet系统
	 * @param paraMap
	 * @return ResponseResult<Object>
	 * @throws Exception
	 * @author: wangxinhua
	 * @date: 2020年11月16日上午10:15
	 * @modify:
	 */
	@GetMapping(value = "/syncTOAWork")
	public ResponseResult<Object> SyncTOAWork(@RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request) {
		try {
			Map syncRes = this.service.syncTOAWork(paraMap);
			if (syncRes.get("success").equals(false)) {
				return ResponseResult.error("同步失败!" + syncRes.get("msg"));
			}
			return ResponseResult.ok("同步成功!");
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}
}
